package com.fubowen.reader.ui.fragment

import android.app.Dialog
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.fubowen.reader.db.ThemeDatabase
import com.fubowen.reader.db.database
import com.fubowen.reader.extension.dpToPx
import com.fubowen.reader.extension.setColor
import com.fubowen.reader.vm.CacheViewModel
import com.fubowen.reader.vm.ThemeViewModel
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.coroutines.launch

const val HEIGHT = "height"

abstract class ThemeBottomSheetDialogFragment : PermissionFragment() {

    open val isEnableOnBack = false
    lateinit var onBackCallback: OnBackPressedCallback

    open val bottomSheetId = com.google.android.material.R.id.design_bottom_sheet
    open var height = 0.5f
    open var radius = 16
    open var paddingLeft = 0
    open var paddingRight = 0
    open var paddingTop = radius
    open var paddingBottom = radius
    open var state = BottomSheetBehavior.STATE_EXPANDED
    open var isDialog = false
    open val cacheViewModel by activityViewModels<CacheViewModel>()
    open lateinit var themeViewModel: ThemeViewModel
    open lateinit var database: ThemeDatabase

    //region 生命周期

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.apply {
            val h = getFloat(HEIGHT)
            height = if (h != 0f) h else height
        }
        database = requireContext().database
        themeViewModel = ViewModelProvider(this)[ThemeViewModel::class.java]
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        setOnBack()
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bsd = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        bsd.behavior.state = state
        return bsd
    }

    override fun onStart() {
        super.onStart()
        if (isDialog) {
            setHeight()
            setBackground()
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        observeTheme()
    }

    //endregion

    //region 设置弹窗属性

    private fun setHeight() {
        val screenHeight = resources.displayMetrics.heightPixels
        val h = when {
            height > 0 && height < 1 -> (screenHeight * height).toInt()
            height >= 1 -> dpToPx(height.toInt())
            else -> -1
        }
        if (h != -1) {
            val layoutParams = requireView().layoutParams
            layoutParams.height = h
            requireView().layoutParams = layoutParams
        }
    }

    private fun setBackground() {
        GradientDrawable().apply {
            shape = GradientDrawable.RECTANGLE
            setColor(themeViewModel.getBackgroundColor())
            cornerRadius = dpToPx(radius).toFloat()
            dialog?.findViewById<FrameLayout>(bottomSheetId)?.let {
                it.setPadding(
                    dpToPx(paddingLeft),
                    dpToPx(paddingTop),
                    dpToPx(paddingRight),
                    dpToPx(paddingBottom)
                )
                it.background = this
            }
        }
    }

    //endregion

    //region observeTheme
    private fun observeTheme() = lifecycleScope.launch {
        themeViewModel.themeFlow.collect {
            if (view != null) {
                themeViewModel.setViewTheme(requireView())
                dialog?.findViewById<FrameLayout>(bottomSheetId)?.background?.setColor(
                    themeViewModel.getBackgroundColor()
                )
            }
        }
    }
    //endregion

    //region 返回监听
    open fun setOnBack() {
        onBackCallback = object : OnBackPressedCallback(isEnableOnBack) {
            override fun handleOnBackPressed() {
                onBackCallback.isEnabled = onBack()
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackCallback)
    }

    open fun onBack(): Boolean {
        return false
    }
    //endregion
}